//
//  YXHomeManageTypeViewController.m
//  CreditCard
//
//  Created by 杨旭 on 2017/12/22.
//  Copyright © 2017年 杨旭. All rights reserved.
//

#import "YXHomeManageTypeViewController.h"
#import "YXQrCodeView.h"
#import "YXAddPartnerTableView.h"
#import "YXWalletHeaderView.h"
#import "YXWithdrawalTableView.h"
#import "YXBankCardTableView.h"
#import "YXAddBankCardTableView.h"
#import "YXWithdrawalDetailTableView.h"
#import "YXCustomAlertActionView.h"
#import "YXNameCertificationView.h"
#import "YXBindingBankCardView.h"
#import "YXCertificationAleatView.h"
#import "YXBankViewModel.h"
#import "YXBankModel.h"
#import "YXShowPayPasswordView.h"
#import "YXMineSettingTypeViewController.h"
#import <TencentOpenAPI/QQApiInterface.h>
#import "UMSocial.h"
#import "WXApi.h"
#import "WeiboSDK.h"
@interface YXHomeManageTypeViewController ()<UMSocialUIDelegate>
@property (nonatomic ,strong) YXQrCodeView *codeView;
@property (nonatomic ,strong) YXAddPartnerTableView *addTableView;
@property (nonatomic ,strong) YXWalletHeaderView *walletHeaderView;
@property (nonatomic ,strong) YXWithdrawalTableView *withdrawalTableView;
@property (nonatomic ,strong) YXWithdrawalDetailTableView *wdDetailTableView;
@property (nonatomic ,strong) YXBankCardTableView *bankCardTableView;
@property (nonatomic ,strong) YXAddBankCardTableView *addBankCardTableView;
@property (nonatomic ,strong) YXNameCertificationView *nameView;
@property (nonatomic ,strong) YXBindingBankCardView *bindingBankCardView;
@property (nonatomic ,strong) YXShowPayPasswordView *payPasswordView;
@property (nonatomic ,strong) YXBankModel *bankModel;
@end

@implementation YXHomeManageTypeViewController

- (YXQrCodeView *)codeView {
    if (!_codeView) {
        _codeView = [[YXQrCodeView alloc] initWithFrame:self.view.bounds];
        YXWeakSelf
        [_codeView setClickShareBtnBlock:^{
            //友盟
            [UMSocialData setAppKey:@"57779f98e0f55a2de90012f1"];
            
            //存放当前显示的分享平台
            NSMutableArray *plantFormArr = [[NSMutableArray alloc] init];
            //添加短信平台
            [plantFormArr addObject:UMShareToSms];
            //判断当前是否安装微信，添加微信好友、朋友圈、和收藏
            if ([WXApi isWXAppInstalled]) {
                [plantFormArr addObject:UMShareToWechatSession];
                [plantFormArr addObject:UMShareToWechatTimeline];
                //            [plantFormArr addObject:UMShareToWechatFavorite];
            }
            //判断是否安装qq，添加qq好友和qq空间平台
            if ([QQApiInterface isQQInstalled]) {
                [plantFormArr addObject:UMShareToQQ];
                [plantFormArr addObject:UMShareToQzone];
                [UMSocialData defaultData].extConfig.qzoneData.title = @"卡友";
                [UMSocialData defaultData].extConfig.qzoneData.url = @"www.baidu.com";
                [[UMSocialData defaultData].urlResource setResourceType:UMSocialUrlResourceTypeImage url:@"http://121.199.38.85/guancheyi/public/uploads/event_img/user_4/2015091717/55fa8b5cdd03b.jpg"];
            }
            //判断是否安装新浪微博
            if ([WeiboSDK isWeiboAppInstalled]) {
                [plantFormArr addObject:UMShareToSina];
            }
            
            [UMSocialSnsService presentSnsIconSheetView:weakSelf
                                                 appKey:@"558a3b9767e58edac60036e4"
                                              shareText:@"南京守易众，www.baidu.com"
                                             shareImage:[UIImage imageNamed:@"icon.png"]
                                        shareToSnsNames:plantFormArr  //微信好友、朋友圈、微信收藏、短信
                                               delegate:weakSelf];
        }];
    }
    return _codeView;
}

- (YXAddPartnerTableView *)addTableView {
    if (!_addTableView) {
        _addTableView = [[YXAddPartnerTableView alloc] initWithFrame:self.view.bounds style:(UITableViewStylePlain)];
        YXWeakSelf
        // 发送短信
        [_addTableView setCodeBtnClickBlock:^(NSString *phone) {
            //    http://121.196.210.134:8082/mpos/wx/sendRegisterSmsCode.do
            NSString *urlStr = @"sendRegisterSmsCode.do";
            NSDictionary *parameter = @{@"phone":phone};
            [BX_NetWorkManager requestForPOSTWithUrl:urlStr parameter:parameter success:^(id responseObject) {
                if (REQUESTDATASUCCESS) {
                    [weakSelf showAlertWithTitle:@"提示" Messge:@"手机短信发送成功！"];
                }
            } failure:^(NSError *error) {
                NSLog(@"%@",error);
                [weakSelf showAlertWithTitle:@"提示" Messge:@"此号码已经被注册过！"];
            }];
        }];
        
        // 添加合伙人
        [_addTableView setSelectAddBtnClick:^(NSDictionary *dict) {
//        http://121.196.210.134:8082/mpos/wx/insertUserAndAgent.do
//            NSString *urlStr = @"insertUserAndAgent.do";
//            NSDictionary *parameter = @{@"sessionId":[YXUserInfoManager getUserInfo].sessionId,@"userName":dict[@"userName"],@"account":dict[@"account"],@"password":dict[@"password"],@"password2":dict[@"password2"],@"smsCode":dict[@"smsCode"]};
//            [BX_NetWorkManager requestForPOSTWithUrl:urlStr parameter:parameter success:^(id responseObject) {
//                if (REQUESTDATASUCCESS) {
//                    [weakSelf showAlertWith:@"恭喜您添加合伙人成功！"];
//                }
//            } failure:^(NSError *error) {
//                NSLog(@"%@",error);
//                [weakSelf showAlertWithTitle:@"提示" Messge:@"维护中，请稍等！"];
//
//            }];
            
            NSString *pwd = [[weakSelf passwordToMD5:dict[@"password"]] lowercaseString];
            NSString *pwd2 = [[weakSelf passwordToMD5:dict[@"password2"]] lowercaseString];
            
            NSString *str = [[NSString stringWithFormat:@"insertUserAndAgent.do?sessionId=%@&userName=%@&account=%@&password=%@&password2=%@&smsCode=%@",[YXUserInfoManager getUserInfo].sessionId, dict[@"userName"], dict[@"account"],pwd,pwd2,dict[@"smsCode"]] stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
            
            [BX_NetWorkManager requestForGETWithUrl:str parameter:nil success:^(id responseObject) {
                if (REQUESTDATASUCCESS) {
                    [weakSelf showAlertWith:@"恭喜您添加合伙人成功！"];
                }
            } failure:^(NSError *error) {
                NSLog(@"%@",error);
                [weakSelf showAlertWithTitle:@"提示" Messge:@"维护中，请稍等！"];
                
            }];
            
        }];
        
   
    }
    return _addTableView;
}

- (YXWalletHeaderView *)walletHeaderView {
    if (!_walletHeaderView) {
        _walletHeaderView = [[YXWalletHeaderView alloc] initWithFrame:(CGRectMake(0, 0, kScreenWidth, 150))];
        YXWeakSelf
        [_walletHeaderView setReleaseBtnClickBlock:^{
            YXHomeManageTypeViewController *typeVC = [[YXHomeManageTypeViewController alloc] init];
            typeVC.title = @"银行卡";
            typeVC.type = 3;
            [weakSelf.navigationController pushViewController:typeVC animated:YES];
            
            [typeVC setSelectBankCardNumberBlock:^(YXBankModel *bankModel) {
                weakSelf.bankModel = bankModel;
                [weakSelf.walletHeaderView setCardNumber:weakSelf.bankModel.bankNo];
            }];
        }];
    }
    return _walletHeaderView;
}

- (YXWithdrawalTableView *)withdrawalTableView {
    if (!_withdrawalTableView) {
        _withdrawalTableView = [[YXWithdrawalTableView alloc] initWithFrame:(CGRectMake(0, 150, kScreenWidth, kScreenHeight - 150)) style:(UITableViewStylePlain)];
        
        YXWeakSelf
        [_withdrawalTableView setClickWithdrawalBtnBlock:^(NSString *price) {
            
            _payPasswordView = [[YXShowPayPasswordView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight)];
            
            // 分润提现
            [weakSelf.payPasswordView setPushResultsView:^(NSString *password){
                NSLog(@"%@",password);
                // MD5加密
                NSString *pwd = [[weakSelf passwordToMD5:password] lowercaseString];
                
                [YXBankViewModel getQueryCashProfitSessionId:[YXUserInfoManager getUserInfo].sessionId BankId:weakSelf.bankModel.bankNo == nil  ?[YXUserInfoManager getUserInfo].idCard : weakSelf.bankModel.bankNo Price:price Password:pwd ModelList:^(NSString *price) {

                    NSLog(@"%@",price);
                    YXHomeManageTypeViewController *typeVC = [[YXHomeManageTypeViewController alloc] init];
                    typeVC.type = 5;
                    typeVC.price = price;
                    [weakSelf.navigationController pushViewController:typeVC animated:YES];

                } Failure:^(NSError *error) {
                    NSLog(@"请求失败:%@",error);
                    [weakSelf showAlertWithTitle:@"维护中，请稍等！"];
                }];
            }];
            
            [weakSelf.payPasswordView setPushRetrievePasswordView:^{
                YXMineSettingTypeViewController *settingTypeVC = [[YXMineSettingTypeViewController alloc] init];
                settingTypeVC.title = @"找回提现密码";
                settingTypeVC.typeView =WithdrawalPasswordView;
                [weakSelf.navigationController pushViewController:settingTypeVC animated:YES];
            }];
            
            [weakSelf.payPasswordView showPayPasswordView];
        }];
    }
    return _withdrawalTableView;
}

- (YXWithdrawalDetailTableView *)wdDetailTableView {
    if (!_wdDetailTableView) {
        _wdDetailTableView = [[YXWithdrawalDetailTableView alloc] initWithFrame:self.view.bounds style:(UITableViewStylePlain)];
        _wdDetailTableView.price = self.price;
        
        YXWeakSelf
        [_wdDetailTableView setPushRootView:^{
            [weakSelf.navigationController popToRootViewControllerAnimated:YES];
        }];
    }
    return _wdDetailTableView;
}

- (YXBankCardTableView *)bankCardTableView {
    if (!_bankCardTableView) {
        _bankCardTableView = [[YXBankCardTableView alloc] initWithFrame:self.view.bounds style:(UITableViewStylePlain)];
        YXWeakSelf
        // 选择银行卡号
        [_bankCardTableView setSelectBankCardNumberBlock:^(YXBankModel *bankModel) {
            
            if (weakSelf.selectBankCardNumberBlock) {
                weakSelf.selectBankCardNumberBlock(bankModel);
            }
            [weakSelf.navigationController popViewControllerAnimated:YES];
            
        }];
        
        // 跳转添加银行卡界面
        [_bankCardTableView setAddBankCardClickBlock:^{
            YXHomeManageTypeViewController *typeVC = [[YXHomeManageTypeViewController alloc] init];
            typeVC.title = @"添加银行卡";
            typeVC.type = 4;
            [weakSelf.navigationController pushViewController:typeVC animated:YES];
            
        
        }];
        
        
        // 删除银行卡
        [_bankCardTableView setDelAccountBlock:^(NSString *ID) {
            //            http://121.196.210.134:8082/mpos/wx/deleteBank.do
            NSString *urlStr = @"deleteBank.do";
            NSDictionary *parameter = @{@"sessionId":[YXUserInfoManager getUserInfo].sessionId,@"id":ID};
            [BX_NetWorkManager requestForPOSTWithUrl:urlStr parameter:parameter success:^(id responseObject) {
                
                if (REQUESTDATASUCCESS) {
                    NSLog(@"%@",responseObject);
                }
            } failure:^(NSError *error) {
                [weakSelf showAlertWith:@"维护中，请稍等！"];
            }];
        }];
    }
    return _bankCardTableView;
}

- (YXAddBankCardTableView *)addBankCardTableView {
    if (!_addBankCardTableView) {
        _addBankCardTableView = [[YXAddBankCardTableView alloc] initWithFrame:self.view.bounds style:(UITableViewStylePlain)];
        
        YXWeakSelf
        // 添加银行卡
        [_addBankCardTableView setAddBankCardBlock:^(NSDictionary *dict) {
            //            http://121.196.210.134:8082/mpos/wx/addBank.do
            NSString *urlStr = @"addBank.do";
            NSDictionary *parameter = @{@"sessionId":[YXUserInfoManager getUserInfo].sessionId,@"cardName":[YXUserInfoManager getUserInfo].name, @"bankNo":dict[@"bankNo"],@"phone":dict[@"phone"],@"vCode":dict[@"vCode"]};
            [BX_NetWorkManager requestForPOSTWithUrl:urlStr parameter:parameter success:^(id responseObject) {
                
                if (REQUESTDATASUCCESS) {
                    [weakSelf showAlertWith:@"添加成功！"];
                }
            } failure:^(NSError *error) {
                [weakSelf showAlertWithTitle:@"提示" Messge:@"维护中，请稍等！"];
            }];
            
        }];
    }
    return _addBankCardTableView;
}

- (YXNameCertificationView *)nameView {
    if (!_nameView) {
        _nameView = [[YXNameCertificationView alloc] initWithFrame:self.view.bounds];
        
        [_nameView setSelectReferBtnClickBlock:^(NSInteger index) {
            YXCertificationAleatView *aleatView = [[YXCertificationAleatView alloc] initWithFrame:[UIScreen mainScreen].bounds];
            [aleatView showCustomAlertView];
            if (index == 0) {
                aleatView.picImageView.image = [UIImage imageNamed:@"正"];
            }else {
                aleatView.picImageView.image = [UIImage imageNamed:@"反"];

            }
        
        }];
    }
    return _nameView;
}

- (YXBindingBankCardView *)bindingBankCardView {
    if (!_bindingBankCardView) {
        _bindingBankCardView = [[YXBindingBankCardView alloc] initWithFrame:self.view.bounds];
        
        // 实名认证
        YXWeakSelf
        [_bindingBankCardView setClickCompleteBtnBlock:^(NSDictionary *dataDic) {
            
            NSString *wPassword = [[weakSelf passwordToMD5:dataDic[@"wPassword"]] lowercaseString];
             NSString *cPassword = [[weakSelf passwordToMD5:dataDic[@"cPassword"]] lowercaseString];
            
            [YXBankViewModel getQueryBensureCardName:weakSelf.name idCardFrontImgUrl:weakSelf.idCardFrontImgUrl idCardBackImgUrl:weakSelf.idCardBackImgUrl bankNo:dataDic[@"bankNo"] phone:dataDic[@"phone"] vCode:dataDic[@"vCode"] wPassword:wPassword cPassword:cPassword  ModelList:^(NSArray *listArr) {
                
                [weakSelf showAlertWith:@"恭喜您完成认证！"];
                
            } Failure:^(NSError *error) {
                [weakSelf showAlertWithTitle:@"提示" Messge:@"维护中，请稍等！"];
            }];
            
        }];
    }
    return _bindingBankCardView;
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
  
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    [self createLeftBarButtonItemWithImage:@"导航栏_002"];
    [self createUI];
    
}

- (void)createUI {
    
    switch (self.type) {
        case 0:
        {
            [self.view addSubview:self.codeView];
        }
            break;
        case 1:
        {
             [self.view addSubview:self.addTableView];
        }
            break;
        case 2:
        {
            YXUserInfoModel *model = [YXUserInfoManager getUserInfo];
            if ([model.certification isEqualToString:@"已认证"]) {
                [self.view addSubview:self.walletHeaderView];
                [self.view addSubview:self.withdrawalTableView];
            }else {
                [self setWithRealName];
            }
     
        }
            break;
        case 3:
        {
            [self.view addSubview:self.bankCardTableView];
            [YXBankViewModel getQueryBankListSessionId:[YXUserInfoManager getUserInfo].sessionId ModelList:^(NSArray *listArr) {
                self.bankCardTableView.dataArr = [NSMutableArray arrayWithArray:listArr];
            } Failure:^(NSError *error) {
                [self showAlertWithTitle:@"提示" Messge:@"维护中，请稍等！"];

            }];
            
        }
            break;
        case 4:
        {
            [self.view addSubview:self.addBankCardTableView];
        }
            break;
        case 5:
        {
            [self.view addSubview:self.wdDetailTableView];
        }
            break;
        case 6:
        {
            [self createNameNarUI];
            [self.view addSubview:self.nameView];
            
        }
            break;
        case 7:
        {
            [self.view addSubview:self.bindingBankCardView];
            
            
        }
            break;
        default:
            break;
    }
    
}

- (void)createNameNarUI {
    UIBarButtonItem *rightItem = [[UIBarButtonItem alloc] initWithTitle:@"下一步" style:(UIBarButtonItemStyleDone) target:self action:@selector(determineBtnAction)];
    rightItem.tintColor = [UIColor whiteColor];
    self.navigationItem.rightBarButtonItem = rightItem;
    UIBarButtonItem *leftItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"导航栏_002"] style:(UIBarButtonItemStyleDone) target:self action:@selector(leftBarButtonItem)];
    self.navigationItem.leftBarButtonItem = leftItem;
}

- (void)leftBarButtonItem {
    [self.navigationController popToRootViewControllerAnimated:YES];
}

- (void)determineBtnAction {
    
    if (self.nameView.nameTF.text.length == 0 || self.nameView.codeTF.text.length == 0 || self.nameView.picImageView.image == nil || self.nameView.picImageView2.image == nil) {
        [self showTostMessage:@"姓名、身份证号、身份证正反面必填！"];
    }else {
        YXHomeManageTypeViewController *typeVC = [[YXHomeManageTypeViewController alloc] init];
        typeVC.title = @"绑定银行卡";
        typeVC.type = 7;
        typeVC.name = self.nameView.nameTF.text;
        typeVC.idCardBackImgUrl = self.nameView.imageData;
        typeVC.idCardFrontImgUrl = self.nameView.imageData2;
        [self.navigationController pushViewController:typeVC animated:YES];
    }
    
  
}

#pragma mark - 判断实名认证
- (void)setWithRealName {
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"请完成实名认证" message:@"" preferredStyle:(UIAlertControllerStyleAlert)];
    
    UIAlertAction *alert = [UIAlertAction actionWithTitle:@"关闭" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
        [self.navigationController popViewControllerAnimated:YES];
    }];
    
    UIAlertAction *alert1 = [UIAlertAction actionWithTitle:@"立即完成" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
        YXHomeManageTypeViewController *typeVC = [[YXHomeManageTypeViewController alloc] init];
        typeVC.title = @"实名认证";
        typeVC.type = 6;
        [self.navigationController pushViewController:typeVC animated:YES];
    }];
    [alertController addAction:alert];
    [alertController addAction:alert1];
    [self presentViewController:alertController animated:YES completion:nil];
}

@end
